import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/enterprise_auth_zhifu/title_top_widget.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import '../wallet/wallet_controller.dart';
import 'dart:io' show Platform;


class MyWebViewZhifuOpenPage extends StatefulWidget {
  const MyWebViewZhifuOpenPage({super.key});
  static const path = '/MyWebViewZhifuOpenPage';

  @override
  State<MyWebViewZhifuOpenPage> createState() => _MyWebViewPageState();
}

class _MyWebViewPageState extends State<MyWebViewZhifuOpenPage> with WidgetsBindingObserver {

  final RxDouble _progress = 0.0.obs;
  late var url = '';
  late var showWebView = true;
  @override
  void initState() {
    super.initState();
    _checkPermissions();
    try {
      final params = Get.parameters ?? {};
      final args = Get.arguments ?? {};
      var getUrl = params['url'] ?? args['url'];

      if (getUrl != null) {
        url = Uri.decodeComponent(getUrl);
        // print('$getUrl ==== getUrl');
      } else {
        Get.back();
        Get.snackbar('错误', 'URL 无效');
      }
    } catch (e) {
      debugPrint('解析 URL 失败: $e');
      Get.back();
      Get.snackbar('错误', 'URL 格式不正确');
    }

    WidgetsBinding.instance.addObserver(this);
  }
  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
      // 应用从后台回到前台，所有页面都会触发
        // if(isJump){
        //   if (webViewController != null) {
        //     webViewController?.reload();
        //   }
        // }
        break;
      case AppLifecycleState.inactive:
      case AppLifecycleState.paused:
      case AppLifecycleState.detached:
      // 应用进入后台
        break;
      case AppLifecycleState.hidden:
        // TODO: Handle this case.
        throw UnimplementedError();
    }
  }


  InAppWebViewController? webViewController;
  // 在 _MyWebViewPageState 类中
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        WalletController walletController = Get.find();
        walletController.zhifuIsRefresh = true;
        if (await webViewController!.canGoBack()) {
          webViewController!.goBack();
          return false; // 阻止默认返回行为
        }
        return true; // 允许关闭当前页面
      },
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: SafeArea(top: false,child: Padding(
          padding: EdgeInsets.only(left: 0.px, top: 20.px, right: 0.px),
          child: Column(
            children: [
              TitleTopWidget(title:"",titleColor: AppColors.fontColor,
                onLeftPressed: () {
                  WalletController walletController = Get.find();
                  walletController.zhifuIsRefresh = true;
                },
              ),
              hiSpace(height: 10.px),
              _buildProgressBar(),
              Expanded(child:  Container(
                child: IndexedStack(
                  index: showWebView ? 0 : 1,
                  children: [
                    _buildWebView(), Container()],
                ),
                //  _buildWebView()
              ))

            ],
          ),
        )),
      ),
    );
  }

  Widget _buildWebView() {
    return InAppWebView(
      initialUrlRequest: URLRequest(url: WebUri(url)),
      initialOptions: InAppWebViewGroupOptions(
        crossPlatform: InAppWebViewOptions(
          mediaPlaybackRequiresUserGesture: false,
          javaScriptEnabled: true,
          javaScriptCanOpenWindowsAutomatically: true,
          // useShouldOverrideUrlLoading: true, // 使用shouldOverrideUrlLoading事件
        ),
        android: AndroidInAppWebViewOptions(
          useHybridComposition: true,
          allowFileAccess: true,
          useShouldInterceptRequest: true,
        ),
        ios: IOSInAppWebViewOptions(
            allowsInlineMediaPlayback: true,
            isFraudulentWebsiteWarningEnabled: false),
      ),
      onWebViewCreated: (controller) {
        webViewController = controller;
      },
      onPermissionRequest: (controller, request) async {
        // 处理网页内的权限请求
        return PermissionResponse(
          resources: request.resources,
          action: PermissionResponseAction.GRANT,
        );
      },
      onProgressChanged: (controller, progress) {
        _progress.value = progress / 100;
      },
      onLoadStart: (controller, url) {
        // debugPrint('alipays URL : $url');
        if (url.toString().contains('alipays:')) {
          launch('${url.toString()}');
          if (!Platform.isIOS) {
            setState(() {
              showWebView = false;
            });
            controller.goBack().then((r) {
              Future.delayed(const Duration(milliseconds: 1000), () {
                setState(() {
                  showWebView = true;
                });
              });
            });
          }
        }
      },
      onLoadStop: (controller, url) {},

      onLoadError: (controller, url, code, message) {
        // debugPrint('onLoadError url : $url  code: $code message: $message');
        if (Platform.isIOS) {
          debugPrint('当前设备是iOS');
          if (url.toString().contains('alipays://platformapi/startapp?appId')) {
            launch('${url.toString()}');
          }
        } else {
          debugPrint('当前设备不是iOS');
            controller.goBack().then((r) {
              Future.delayed(const Duration(milliseconds: 1000), () {
                setState(() {
                  showWebView = true;
                });
              });
            });
        }
      },
      shouldOverrideUrlLoading: (controller, navigationAction) async {},
    );
  }

  Widget _buildProgressBar() {
    return LinearProgressIndicator(
      minHeight: 1.px,
      color: const Color(0xFFFFFFFF),
      value: _progress.value,
    );
  }
  Future<void> _checkPermissions() async {
    // 请求摄像头和麦克风权限
    final status = await [Permission.camera, Permission.microphone].request();

    if (status[Permission.camera]!.isGranted &&
        status[Permission.microphone]!.isGranted) {
    } else {
      Get.snackbar('权限被拒绝', '请前往设置开启权限');
    }
  }
}
